<!-- 生产管理 班组登记 -->
<template>
  <basic-container>
    <avue-crud
      v-model="form"
      class="inoutFrom"
      ref="crud"
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          icon="el-icon-plus"-->
        <!--          size="small"-->
        <!--          v-if="permission.classGroupRegister_goToWorkRegistration && allowRegister && !loading"-->
        <!--          @click="rowAdd"-->
        <!--          :disabled="data.filter((d) => d.$cellEdit).length > 0"-->
        <!--          >上班登记</el-button-->
        <!--        >-->
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          icon="el-icon-finished"-->
        <!--          size="small"-->
        <!--          v-if="permission.classGroupRegister_registrationCompleted && allowRegister && !loading"-->
        <!--          :disabled="finishDisabled"-->
        <!--          @click="rowCell"-->
        <!--          >登记完成</el-button-->
        <!--        >-->
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <!-- <template slot-scope="{ row, index }" slot="menu">
        <el-button v-if="row.$cellEdit" type="text" size="small" @click="rowCell(row, index)">登记完成</el-button>
        <el-button v-if="row.$cellEdit" type="text" size="small" @click="$refs.crud.rowCancel(row, index)">取消</el-button>
      </template> -->
    </avue-crud>
    <!--公用模态弹框-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { shiftGroupRegister, pageShiftGroupRegister, queryLine, remove } from '@/api/product/classGroupRegister';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';

export default {
  components: {
    userTableConfig,
    commonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'CLASS_GROUP_REGISTER',
      isAllotClassGroup: true, // 分配班组
      allowDisabled: false, // 上班登记按钮
      finishDisabled: true, // 登记完成按钮是否禁用
      allowRegister: true, // 按钮显示隐藏
      addData: {},
      form: {},
      query: {},
      defaults: {},
      loading: true,
      data: [],
      commonDialog: {
        dispatch: true
      },
      tableOption: {}, //公用模态框配置信息
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        addBtnText: '新增登记',
        cellBtn: false,
        viewBtn: true,
        editBtn: true,
        delBtn: true,
        selection: false,
        dialogClickModal: false,
        menu: true,
        labelWidth: 120,
        menuWidth: 220,
        searchLabelWidth: 50,
        columnBtn: false,
        column: [
          {
            label: '时间',
            type: 'datetimerange',
            prop: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '时间日期开始范围',
            endPlaceholder: '时间日期结束范围',
            order: 1,
            hide: true,
            search: true,
            display: false,
            editDisplay: false,
            viewDisplay: false,
            searchSpan: 7,
            searchType: 'daterange'
          },
          {
            label: '车间',
            prop: 'workshopId',
            order: 1,
            type: 'select',
            dicUrl: '/api/mes-product/workshop/page?current=1&size=100000',
            dicFormatter: (res) => {
              this.workshop = res.data.records || [];
              return res.data.records || [];
            },
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请选择车间',
                trigger: 'blur'
              }
            ],
            change: (val) => {
              this._forEach(this.workshop, (item) => {
                if (val.value === item.id) {
                  this.form.workshopName = item.name;
                }
              });
            }
          },
          {
            label: '产线',
            prop: 'lineName',
            type: 'search',
            order: 2,
            appendClick: () => {
              this.openProductLineCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择产线',
                trigger: 'blur'
              }
            ],
            enter: (val) => {
              this.queryLineInfo(val);
            }
          },
          {
            label: '班组',
            prop: 'shiftGroupId',
            dicUrl: '/api/mes-admin/shift-group/page?current=1&size=100000',
            dicFormatter: (res) => {
              this.shiftGroupInfo = res.data.records || [];
              return res.data.records || [];
            },
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请选择班组',
                trigger: 'blur'
              }
            ],
            order: 3,
            type: 'select',
            change: (val) => {
              this._forEach(this.shiftGroupInfo, (item) => {
                if (val.value === item.id) {
                  // let saberUserInfo = localStorage.getItem('saber-userInfo');
                  // if (saberUserInfo && saberUserInfo != '{}') {
                  //   this.form.principalId = JSON.parse(saberUserInfo).content.user_id;
                  // }
                  this.form.principleName = item.principleName;
                  this.form.shiftGroupUserNumber = item.shiftGroupCount;
                  this.form.shiftGroupName = item.name;
                }
              });
            }
          },
          {
            label: '班组长',
            prop: 'principleName',
            disabled: true
          },
          {
            label: '班组人数',
            prop: 'shiftGroupUserNumber',
            type: 'number',
            disabled: true
          },
          {
            label: '班次',
            prop: 'shiftId',
            type: 'select',
            dicUrl: '/api/mes-admin/shift/page?current=1&size=10000',
            dicFormatter: (res) => {
              this.shiftInfo = res.data.records || [];
              return res.data.records || [];
            },
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请选择班次',
                trigger: 'blur'
              }
            ],
            change: (val) => {
              this._forEach(this.shiftInfo, (item) => {
                if (val.value === item.id) {
                  this.form.shiftName = item.name;
                }
              });
            }
          },
          {
            label: '实出勤人数',
            prop: 'actualAttendance',
            type: 'number',
            minRows: 0,
            row: true,
            // maxRows: 1,
            rules: [
              {
                required: true,
                message: '请输入实出勤人数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '登记时间',
            prop: 'createTime',
            type: 'datetime',
            disabled: true,
            order: 1,
            display: false,
            row: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            row: true,
            span: 24,
            minRows: 3 //定义多行文本最小行数
          }
        ]
      },
      shiftGroupInfo: [],
      shiftInfo: [],
      workshop: []
    };
  },

  computed: {
    ...mapGetters(['permission'])
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      shiftGroupRegister(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      shiftGroupRegister(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove({ ids: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    // // 查询班组信息
    // getShiftGroupInfo() {
    //   queryShiftGroupInfo()
    //     .then((res) => {
    //       if (res && res.status == 200) {
    //         this.shiftGroupInfo = res.data.data;
    //         if (this.shiftGroupInfo && this.shiftGroupInfo.length > 0) {
    //           let workShopColumn = this.findObject(this.option.column, 'workshopId');
    //           workShopColumn.dicData = [];
    //           this._forEach(this.shiftGroupInfo, (item) => {
    //             let workShopIndex = this._findIndex(workShopColumn.dicData, { value: item.workshopId });
    //             if (workShopIndex === -1) {
    //               workShopColumn.dicData.push({ label: item.workshopName, value: item.workshopId });
    //             }
    //           });
    //           let shiftGroupIdColumn = this.findObject(this.option.column, 'shiftGroupId');
    //           shiftGroupIdColumn.dicData = [];
    //           this._forEach(this.shiftGroupInfo, (item) => {
    //             shiftGroupIdColumn.dicData.push({ label: item.shiftGroupName, value: item.shiftGroupId });
    //           });
    //         } else {
    //           this.$message.warning('当前用户无法登记班组信息');
    //         }
    //       }
    //     })
    //     .finally(() => {
    //       this.finishDisabled = true;
    //     });
    // },
    getSelectedRows(rowData) {
      this.form.lineId = this._get(rowData, 'id', '');
      this.form.lineCode = this._get(rowData, 'code', '');
      this.form.lineName = this._get(rowData, 'name', '');
      this.checkLine(rowData.workshopId || '');
    },
    async queryLineInfo(name) {
      try {
        const params = {
          nameInfo: name
        };
        const res = await queryLine(params);
        const data = res.data.data || [];
        if (!data.length) {
          this.$message.error('该产线不存在');
          this.form.lineName = '';
        } else {
          const [item] = data;
          this.form.lineId = this._get(item, 'id', '');
          this.form.lineCode = this._get(item, 'code', '');
          this.form.lineName = this._get(item, 'name', '');
        }
      } catch (e) {}
    },
    checkLine(id) {
      if (this.form.workshopId !== id) {
        this.form.lineId = '';
        this.form.lineCode = '';
        this.form.lineName = '';
        this.$message.error(`该产线不属于${this.form.$workshopId}`);
      }
    },
    openProductLineCommonModal() {
      this.modalName = 'lineModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产线信息（双击进行选择）',
        url: '/api/mes-product/product/line/list',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true
          },
          {
            label: '产线编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.query.datetimerange) {
        this.query.startTime = this.query.datetimerange[0];
        this.query.endTime = this.query.datetimerange[1];
        delete this.query.datetimerange;
      }
      pageShiftGroupRegister(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>
